package com.kgc.novel.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kgc.novel.common.Res;
import com.kgc.novel.dao.BookAdminMapper;
import com.kgc.novel.domain.entity.BookAdmin;
import com.kgc.novel.domain.param.BookAdminParam;
import com.kgc.novel.service.admin.BookAdminService;
import com.kgc.novel.util.JwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Map;

@Service
@Transactional(rollbackFor = Exception.class)
public class BookAdminServiceImpl extends ServiceImpl<BookAdminMapper, BookAdmin> implements BookAdminService {

    @Resource
    private BookAdminMapper adminMapper;


    @Resource
    private JwtUtil jwtTokenUtil;

    @Override
    public Res<BookAdmin> login(BookAdminParam param) {
        LambdaQueryWrapper<BookAdmin> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(BookAdmin::getAdminName, param.getAdminName());

        BookAdmin admin = adminMapper.selectOne(lambdaQueryWrapper);
        if (admin == null) {
            return Res.returnMsg("账号不存在，请重新输入");
        } else {
            String password = DigestUtil.md5Hex(param.getPassword());
            if (admin.getPassword().equals(password)) {
                admin.setPassword("");
                // 通过 jwtTokenUtil 生成 JWT 令牌和刷新令牌
                Map<String, Object> tokenMap = jwtTokenUtil
                        .generateTokenAndRefreshToken(admin.getAdminId(), admin.getAdminName());
//                admin.setToken("Bearer Token");
                admin.setToken("Bearer " + tokenMap.get("access_token").toString());
                admin.setRefreshToken("Bearer " + tokenMap.get("refresh_token").toString());
                admin.setExpireIn(Long.valueOf(tokenMap.get("expire_in").toString()));
                return Res.returnData(admin);
            } else {
                return Res.returnMsg("密码输入错误，请重新输入");
            }
        }
    }
}